<?php
declare (strict_types = 1);

namespace app\model;

use app\common\model\CacheRefreshHandler;
use app\common\service\redis\PoolRedis;
use think\Model;
use think\model\relation\BelongsTo;

/**
 * @mixin \think\Model
 */
class AdminSuperSim extends Model
{
    //
    protected $autoWriteTimestamp = true;

    public function school(): BelongsTo {
        return $this->belongsTo(AdminSchool::class, 'school_id')->bind([
            'school_name' => 'name'
        ]);
    }

    public function staff(): BelongsTo {
        return $this->belongsTo(AdminStaff::class, 'staff_id')->bind([
            'staff_name' => 'name',
            'staff_type' => 'type',
            'staff_type_text' => 'type_text',
            'student_no',
            'sex',
        ]);
    }

    public static function onAfterWrite($adminSuperSim)
    {
        if ($adminSuperSim->getAttr('is_delete') == 0 && $adminSuperSim->getAttr('nfc_id') != '') {
            $redis = PoolRedis::instance();
            $redis->hSetNx("smartCards", $adminSuperSim->getAttr('nfc_id'), $adminSuperSim->getAttr('staff_id'));
        } elseif ($adminSuperSim->getAttr('is_delete') == 1) {
            $redis = PoolRedis::instance();
            $redis->hDel("smartCards", $adminSuperSim->getAttr('nfc_id'));
            // 删除IC卡号
            AdminStaffIcCard::update([
                'ic_card' => '',
                'whitelist_no' => '',
                'activate_time' => 0
            ], [
                'staff_id' => $adminSuperSim->getAttr('staff_id'),
                'is_delete' => 0
            ]);
            // 删除在线密码
            CacheRefreshHandler::onLinePwDel($adminSuperSim->staff->uuid);
            // 删除用户在该宿舍的编号
            CacheRefreshHandler::staffNumber($adminSuperSim->getAttr('staff_id'), $adminSuperSim->getAttr('school_id'), $adminSuperSim->getAttr('student_dormitory_id'), 'del');
        }
    }
}
